<?php
/**
 * Created by PhpStorm.
 * User: lichuang
 * Date: 2022/9/21
 * Function: 数据层基类
 */

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

class BaseModel extends ActiveRecord
{
    public static $mysql = null;
    public static $mysql_slave = null;
    public static $slave_db_name = null;

    public function init()
    {
        self::mysql();
    }

    public static function mysql()
    {
        // 主库
        if (self::$mysql == null) {
            self::$mysql = Yii::$app->mysql;
        }
    }

    // 分库
    public static function mysql_slave($db_name)
    {
        if (self::$slave_db_name == null || self::$slave_db_name != $db_name || self::$mysql_slave == null) {

            $dsn = Yii::$app->mysql_slave->dsn . $db_name;
            $username = Yii::$app->mysql_slave->username;
            $password = Yii::$app->mysql_slave->password;

            $connection = new \yii\db\Connection([
                'dsn' => $dsn,
                'username' => $username,
                'password' => $password,
                'charset' => 'utf8mb4'
            ]);
            $connection->open();

            self::$slave_db_name = $db_name;
            self::$mysql_slave = $connection;

        }
        return self::$mysql_slave;
    }
}